var redis = require('redis')
var blubird = require('bluebird')
var client = redis.createClient('6379', '127.0.0.1')
client.on('error', error => {
  console.log(error)
})
client.on('ready', () => console.log('ready'))

blubird.promisifyAll(redis.RedisClient.prototype)
blubird.promisifyAll(redis.Multi.prototype)

new Promise(async (resolve, reject) => {
  // CURD test
  // get
  const firstSetName = await client.getAsync('name') 
  await console.log('first time get name', firstSetName)

  //set 
  await client.setAsync('name', 'Lear', 'EX', 10)
  const getNameAfterSet = await client.getAsync('name')
  await console.log('get name after set', getNameAfterSet)
  setTimeout(() => {
    client.get('get name after 11 seconds', redis.print)
  }, 11000)
  await client.delAsync('name')
  await console.log('after delete', await client.getAsync('name')) 
})
let config = {
  key: 'Koa:sess',
  maxAge: 86400000,
  overwrite: true,
  httpoOnly: true,
  signed: false,
  // 使用redis来持久化Session
  store: {}
}
config.store.get = async function (key) {
  console.log('get key', key)
  var result = await client.getAsync(key)
  console.log('get result', result)
  this.destroy(key)
}
config.store.set = async function (key, sess, maxAge) {
  console.log('set key', key)

  var result = await client.setAsync(key, JSON.stringify(sess))
  console.log('set key', result)
}
config.store.destroy = async function (key) {
  console.log('destory key', key)
}

module.exports = {config}